import webbrowser
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
import os
from mango_service.tools import get_project_path, sep


# Create your views here.
@api_view(["post"])
def soar(request):
    data = JSONParser().parse(request)
    sql = data["sql"]

    sql_path = sep([r"static\soar", "test.sql"], add_after=True)
    html_path = sep([r"static\soar", "test.html"], add_after=True)
    with open(sql_path, 'w', encoding='utf-8') as f:
        f.write(sql)

    command = f"soar -query {sql_path} > {html_path}"
    os.system(command)
    # webbrowser.open(html_path)
    local_link = html_path
    return JsonResponse({"message": "http://127.0.0.1:8000/" + local_link})
